package com.bt.springboot.common.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zkx
 * @Date 2023/5/24 15:18
 */
@Slf4j
@Aspect
@Component
public class OperLogAspect {

	/**
	 * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
	 */
	@Pointcut("@annotation(com.bt.springboot.common.annotation.OperLog)")
	public void operLogPointCut(){
	}

	/**
	 * 设置操作异常切入点记录异常日志 扫描所有controller下的包
	 */
	@Pointcut("execution(* com.bt.springboot.web.controller..*..*(..))")
	public void operExceptionLogPointCut(){
	}

	/**
	 * 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行，如果连接点抛出异常，则不会执行
	 * @param joinPoint
	 * @param keys
	 */
	@AfterReturning(value = "operLogPointCut()",returning = "keys")
	public void saveOperLog(JoinPoint joinPoint,Object keys){

		// 获取RequestAttributes
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
		// 从获取RequestAttributes中获取HttpServletRequest的信息
		HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
		if (request != null){
			log.info("ip:{}",request.getRemoteAddr());
		}
	}
}
